package org.drake.refactor.skill.extract;

public class BinarySearch {

    private static final int LEFT_INIT_VALUE = 0;
    private int left;
    private int right;

    public int binarySearch(int[] nums, int target) {
        left = LEFT_INIT_VALUE;
        right = nums.length - 1;

        while (left <= right) {
            int mid = calculateMid();
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            }
        }

        return -1;
    }

    private int calculateMid() {
        return left + (right - left) / 2;
    }
}
